package com.kingsoft.dc.khaos.plugin.core.utils;

import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文件 工具类.
 * @author tanmengxi
 */
public class FileUtils {


    /**
     * 读文件.
     *
     * @param filePath 路径
     * @return
     */
    public static String readFileAsString(String filePath) {
        String content = "";
        try {
            // 读入文件作为字符串
            content = new String(readAllBytes(get(filePath)));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return content;
    }


    /**
     * 读文件.
     *
     * @param filePath 路径
     * @return
     */
    public static List<String> readFile(String filePath) {
        List<String> lines = new ArrayList<>();
        try {
            // 按行读取文件
            lines = Files.lines(get(filePath), StandardCharsets.UTF_8).collect(Collectors.toList());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return lines;
    }


    /**
     * 写文件.
     *
     * @param filePath 路径
     * @param content  内容
     */
    public static void write2File(String filePath, String content) {
        System.out.println(String.format("本地文件 [ %s ]", filePath));

        Path fpath = Paths.get(filePath);
        //创建文件
        if (!Files.exists(fpath)) {
            try {
                Files.createFile(fpath);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        //创建BufferedWriter
        try {
            BufferedWriter bfw = Files.newBufferedWriter(fpath);
            bfw.write(content);
            bfw.flush();
            bfw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
